package com.lcu.wl.modules.mnt.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lcu.wl.common.exception.SYSException;
import com.lcu.wl.common.utils.FileUtil;
import com.lcu.wl.common.utils.PageUtils;
import com.lcu.wl.common.utils.Query;
import com.lcu.wl.common.utils.StringUtils;
import com.lcu.wl.modules.mnt.entity.Log;
import com.lcu.wl.modules.mnt.mapper.LogMapper;
import com.lcu.wl.modules.mnt.service.ILogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 * <p>
 * 系统日志 服务实现类
 * </p>
 *
 * @author wanglei
 * @since 2021-03-12
 */
@Service("logService")
public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements ILogService {

    @Override
    public PageUtils queryPage(Map<String, Object> params,String logType) {
        String blurry = (String) params.get("blurry");
        String createTime = (String) params.get("createTime");
        String endTime = (String) params.get("endTime");

        QueryWrapper<Log> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(blurry)) {
            queryWrapper.and(qw1 -> qw1.like("username", blurry)
                    .or().like("description", blurry)
                    .or().like("method", blurry)
                    .or().like("params", blurry)
                    .or().like("request_ip", blurry)
                    .or().like("address", blurry));
        }

        if (StringUtils.isNotBlank(createTime) && StringUtils.isNotBlank(endTime)){
            queryWrapper.and(qw2 -> qw2.between("create_time",createTime,endTime));
        }

        IPage<Log> page = this.page(new Query<Log>().getPage(params),
                queryWrapper.eq("log_type", logType)
        );

        return new PageUtils(page);
    }

    @Override
    public void save(String username, String browser, String ip, ProceedingJoinPoint joinPoint, Log log) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        com.lcu.wl.annotation.Log aopLog = method.getAnnotation(com.lcu.wl.annotation.Log.class);

        //方法路径
        String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";

        //描述
        if (log != null) {
            log.setDescription(aopLog.value());
        }
        assert log != null;
        log.setRequestIp(ip);

        log.setAddress(StringUtils.getCityInfo(log.getRequestIp()));
        log.setMethod(methodName);
        log.setUsername(username);
        log.setParams(getParameter(method, joinPoint.getArgs()));
        log.setBrowser(browser);
        log.setCreateTime(new Date());
        this.save(log);
    }

    @Override
    public List<Log> queryAll(Map<String, Object> params,String logType) {
        String blurry = (String) params.get("blurry");
        String createTime = (String) params.get("createTime");
        String endTime = (String) params.get("endTime");

        QueryWrapper<Log> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(blurry)) {
            queryWrapper.and(qw1 -> qw1.like("username", blurry)
                    .or().like("description", blurry)
                    .or().like("method", blurry)
                    .or().like("params", blurry)
                    .or().like("request_ip", blurry)
                    .or().like("address", blurry));
        }

        if (StringUtils.isNotBlank(createTime) && StringUtils.isNotBlank(endTime)){
            queryWrapper.and(qw2 -> qw2.between("create_time",createTime,endTime));
        }

        List<Log> logs = this.list(queryWrapper.eq("log_type", logType));
        return logs;
    }

    @Override
    public void download(List<Log> logs, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Log log : logs) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户名", log.getUsername());
            map.put("IP", log.getRequestIp());
            map.put("IP来源", log.getAddress());
            map.put("描述", log.getDescription());
            map.put("浏览器", log.getBrowser());
            map.put("请求耗时/毫秒", log.getTime());
            map.put("异常详情", new String(ObjectUtil.isNotNull(log.getExceptionDetail()) ? log.getExceptionDetail() : "".getBytes()));
            map.put("创建日期", log.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Object getByErrDetail(Long id) {
        Log log = this.getById(id);
        isNull(log.getLogId(), "Log", "id", id);
        byte[] details = log.getExceptionDetail();
        return Dict.create().set("exception", new String(ObjectUtil.isNotNull(details) ? details : "".getBytes()));
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private String getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return "";
        }
        return argList.size() == 1 ? JSONUtil.toJsonStr(argList.get(0)) : JSONUtil.toJsonStr(argList);
    }

    /**
     * 验证空
     */
    private void isNull(Object obj, String entity, String parameter , Object value){
        if(ObjectUtil.isNull(obj)){
            String msg = entity + " 不存在: "+ parameter +" is "+ value;
            throw new SYSException(msg);
        }
    }
}
